<template>
  <div class="content">
    <category @categoryIdInfo="categoryIdInfo"></category>

    <div class="attrList">
      <el-card v-show="flag">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd()"
          >添加属性</el-button
        >
        <el-table
          :data="productList"
          style="width: 100%; margin-top: 30px"
          border
        >
          <el-table-column label="序号" type="index" width="180" align="center">
          </el-table-column>
          <el-table-column
            label="属性名称"
            width="180"
            prop="attrName"
            align="center"
          >
          </el-table-column>
          <el-table-column header-align="center" label="属性值列表">
            <template slot-scope="scope">
              <el-tag
                style="margin-right: 10px"
                v-for="(attrValue, index) in scope.row.attrValueList"
                :key="index"
                >{{ attrValue.valueName }}</el-tag
              ></template
            >
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card v-show="!flag">
        <div>
          <el-input v-model="productAttr.attrName" style="width: 300px"
            ><template slot="prepend">属性名</template></el-input
          >
        </div>
        <div style="margin: 20px 0">
          <el-button type="primary" icon="el-icon-plus" @click="addAttrVal()"
            >添加属性值</el-button
          ><el-button @click="cancelAttr()">取消</el-button>
        </div>
        <el-table :data="productAttr.attrValueList" style="width: 100%" border>
          <el-table-column type="index" label="序号" width="180" align="center">
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性值名称"
            width="width"
            align="center"
            ><template slot-scope="{ row, $index }"
              ><el-input
                v-if="row.inputFlag"
                v-model="row.valueName"
                :ref="'attrValueInput_' + $index"
                @blur="lossOfFocus(row, $index)"
              ></el-input>
              <p v-else @click="editAttrName(row, $index)">
                {{ row.valueName }}
              </p></template
            >
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="width"
            align="center"
          >
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeAttrVal(row, $index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div style="margin: 20px 0">
          <el-button type="primary" @click="preserveAttrVal()">保存</el-button
          ><el-button @click="cancelAttr()">取消</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import cloneDeep from "lodash/cloneDeep";
import Category from "@/components/Category/index.vue";
export default {
  name: "product",
  data() {
    return {
      id: "", //商品分类id
      categoryThreeValue: "", //三级分类选中的值
      productList: [], // 商品列表
      flag: true, // 是否显示添加属性名
      productAttr: {
        attrName: "",
        attrValueList: [],
      }, // 添加商品属性
      submitProductAttr: {}, // 需要提交的商品属性
    };
  },
  components: {
    Category,
  },
  mounted() {},
  methods: {
    // 子组件回调函数 获取categoryId
    async categoryIdInfo(id) {
      this.id = id;
      this.categoryThreeValue = id.category3Id;
      let res = await this.$api.product.getProductList({ ...this.id });
      if (res.code == 200) {
        this.productList = res.data;
      }
    },
    //删除商品属性
    async handleDelete(index, row) {
      let res = await this.$api.product.deleteAttr(row.id);
      if (res.code == 200) {
        //重新发送请求
        this.categoryIdInfo(this.id, this.categoryThreeValue);
        this.$message.success("删除成功");
      }
    },
    // 编辑商品属性
    handleEdit(index, row) {
      console.log(row);
      this.productAttr = row;
      //备份一下需要提交的数据
      let copiedObject = cloneDeep(row);
      Object.assign(this.submitProductAttr, copiedObject);
      this.flag = false;
    },
    // 添加商品属性
    handleAdd() {
      if (
        this.categoryThreeValue === "" ||
        this.categoryThreeValue === undefined
      ) {
        this.$message.error("请选择三级分类");
        return;
      }
      this.flag = false;
      this.productAttr = {
        attrName: "",
        attrValueList: [],
      };
    },
    // 添加属性值
    addAttrVal() {
      if (this.productAttr.attrName === "") {
        this.$message.error("请输入属性名");
        return;
      }
      let attrVal = { valueName: "", inputFlag: false };
      //添加属性值名称
      this.productAttr.attrValueList.unshift(attrVal);
      this.productAttr.attrValueList[0].inputFlag = true;
      // 获得输入框的焦点
      this.$nextTick(() => {
        this.$refs["attrValueInput_" + 0].focus();
      });
    },
    // 失去焦点
    lossOfFocus(row, index) {
      if (row.valueName === "") {
        // 属性值名称没有，删除自己
        this.productAttr.attrValueList.shift();
        // this.$message.error("属性值名称不能为空");
        // setTimeout(() => {
        //   this.$refs["attrValueInput_" + index].focus();
        // }, 100);
        return;
      }
      // 失去焦点隐藏输入框
      row.inputFlag = false;
    },
    // 编辑属性值名字
    editAttrName(row, index) {
      this.$set(row, "inputFlag", true);
      this.$nextTick(() => {
        this.$refs["attrValueInput_" + index]?.focus();
      });
    },
    //删除属性值名称
    removeAttrVal(row, index) {
      this.productAttr.attrValueList.splice(index, 1);
    },
    // 取消添加属性名
    cancelAttr() {
      this.flag = true;
      let copiedObject = cloneDeep(this.submitProductAttr);
      Object.assign(this.productAttr, copiedObject);
    },
    // 保存属性值
    async preserveAttrVal() {
      // 属性名不能为空
      if (this.productAttr.attrName === "") {
        this.$message.error("属性名不能为空");
        return;
      }
      //属性值名称没有
      if (this.productAttr.attrValueList?.length === 0) {
        this.$message.error("属性值名称不能为空");
        return;
      }
      // 整理数据 {"attrName": "string","attrValueList": [{"valueName": "string"}],categoryLevel: 3,"categoryId": 0}
      this.productAttr.attrValueList.forEach((item) => {
        delete item.inputFlag;
      });
      this.productAttr.categoryLevel = 3;
      this.productAttr.categoryId = this.categoryThreeValue;
      let res = await this.$api.product.addAttr(this.productAttr);
      if (res.code == 200) {
        this.$message.success("添加成功");
        // 数据清空
        this.productAttr = {
          attrName: "",
          attrValueList: [],
        };
        //重新发送请求
        this.categoryIdInfo(this.id, this.categoryThreeValue);
        this.flag = true;
      } else {
        this.$message.error("添加失败");
      }
    },
  },
  computed: {},
};
</script>

<style lang="scss" scoped>
.content {
  margin: 20px;
  .classification {
    display: flex;
    height: 80px;
    align-items: center;
    & div {
      margin-right: 20px;
    }
    & strong {
      margin-left: 10px;
      margin-right: 10px;
    }
  }
  .attrList {
    margin-top: 20px;
  }
}
</style>